有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

xml如何解压java。尼奥。使用JAXB的路径?

我一直在尝试使用JAXB解压一些xml,但我不断收到错误:

java.nio.file.Path is an interface, and JAXB can't handle interfaces.

有没有办法告诉JAXB如何从字符串构建路径

我的班级:

@XmlRootElement
public class Project extends OutputConfiguration {
    private Path sourceDir;
    private Path buildDir;
    private String name;

    /**
     * Get the root directory of the sources.
     * This will be used as the working directory for the build.
     *
     * @return the path
     */
    public Path getSourceDir() {
        return sourceDir;
    }

    /**
     * Get the root directory of the sources.
     *
     * @param sourceDir the path
     */
    @XmlElement
    public void setSourceDir(Path sourceDir) {
        this.sourceDir = sourceDir;
    }

    /**
     * Get the build directory.
     * This is the directory where all outputs will be placed.
     *
     * @return the path
     */
    public Path getBuildDir() {
        return buildDir;
    }

    /**
     * Set the build directory.
     *
     * @param buildDir this is the directory where all outputs will be placed.
     */
    @XmlElement
    public void setBuildDir(Path buildDir) {
        this.buildDir = buildDir;
    }

    /**
     * Get the friendly name of the project.
     *
     * @return the name of the project
     */
    public String getName() {
        return name;
    }

    /**
     * Set the friendly name of the project.
     *
     * @param name the name
     */
    @XmlElement(required = true)
    public void setName(String name) {
        this.name = name;
    }
}

我创建了一个ObjectFactory类,它调用默认构造函数并设置一些默认值


共 (2) 个答案

  1. # 2 楼答案

    这有两个部分,这两个部分都是工作所必需的:


    由于java.nio.file.Path is an interface, and JAXB can't handle interfaces.错误,无法创建XmlAdapter<String, Path>。因此,您必须使用XmlAdapter<String, Object>,因为ObjectPath的超类,所以它是有效的:

    public class NioPathAdaptor extends XmlAdapter<String, Object> {
        public String marshal(Object v) {
            if (!(v instanceof Path)) {
                throw new IllegalArgumentException(...);
            ...
    

    然后必须在属性上使用非常特定的@XmlElement@XmlJavaTypeAdapter

    @XmlJavaTypeAdapter(NioPathAdaptor.class)
    @XmlElement(type = Object.class)
    private Path sourceDir;
    

    type = Object.class告诉JAXB将其序列化,就好像它是一个Object@XmlJavaTypeAdapter表示对该特定字段使用该特定的Object适配器,而不是另一个更通用的适配器